<template>
	<div class="main-box">
		<div v-for="(l, i) in list" class="range-main">
			<div class="range-main__title">{{ getLable(i, l.label) }}：</div>
			<div class="range-main__children">
				<div v-for="c in l.value" @click="change(i, c)" class="range-main__children--item"
					:class="[actived[i]?.key === c.value && 'range-main__children--active']">
					{{ c.label }}
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { RangeListType, RangeValueType } from "./type";

type ActivedType = Record<number, { key: number | string; value: RangeValueType }>;

const props = defineProps<{
	list: RangeListType[];
	levelLabelEnum?: Record<string, string>;
	actived: ActivedType;
}>();
const emits = defineEmits<{
	change: [value: RangeValueType, level: number];
}>();

const actived = ref<ActivedType | any>(props.actived);

const change = (parentIdx: number, item: RangeValueType) => {
	const prev = actived.value[parentIdx];
	if (prev?.key === item.value) {
		Reflect.deleteProperty(actived.value, parentIdx);
	} else {
		actived.value[parentIdx] = {
			key: item.value,
			value: item,
		};
	}

	Object.keys(actived.value).forEach(key => {
		if (Number(key) > parentIdx) actived.value[key] = {};
	});

	emits("change", item, parentIdx);
};

const getLable = (level: number, label?: string) => {
	if (label) return label;
	else if (props.levelLabelEnum) {
		return props.levelLabelEnum[level.toString()];
	}
};

defineExpose({
	getValue: () =>
		Object.values(actived.value)
			.filter((el: any) => el?.value)
			.map((el: any) => el.value) as RangeValueType[],
});
</script>

<style lang="scss" scoped>
@import "./Range.scss";
</style>
